package com.fsbm.ctech.maxis.ebpsbackend;

import java.io.*;
import java.text.*;
import java.util.*;

import com.fsbm.ctech.maxis.ebpsbackend.ConfigObject;
import com.fsbm.ctech.maxis.ebpsbackend.BuildZipSet;

/**
 * Package files from PDF, CSV, body and command file required by the SMTP and SMS
 * Gateway server. The functionality includes zipping of files making it ready for transfer.
 * <p>
 * Maxis Backend Program - Configuration Object to load the config properties file.
 *
 * @author Michael Ty Chan
 */

public class PrepareFiles {
    static ConfigObject cfgObj = new ConfigObject();
    public static void PackageNotifyFiles(String [][] csvFiles) throws IOException {
        String csvFileListName = "";
        String zipReturnFile   = "";
        int listSize           = csvFiles[0].length;
        System.out.println("\nStarting to package files...");

        for (int x=0; x < listSize; x++) {                 // csv email files that were created before
            csvFileListName = csvFiles[0][x];

            if (csvFileListName != null){
                File f = new File(csvFileListName);
                FileInputStream inStream = new FileInputStream(csvFileListName);
                int inBytes = inStream.available();
                inStream.close();
                if (inBytes < 42){
                     f.delete();
                     f = null;
                     csvFileListName = null;
                }
            }

            if (csvFileListName != null){
                // move each csv file from stage to work directory including email body text
                BuildFileSet(csvFileListName, cfgObj.workDirectory);
                // create the command file with the updated command parameter
                BuildCommandFile(csvFileListName, cfgObj.notifyEmailCommand, cfgObj.notifyEmailCommandFileName, cfgObj.workDirectory);
                // Build the body file (created this function for future use)
                BuildBodyFile(cfgObj.notifyEmailTemplate, cfgObj.workDirectory, cfgObj.notifyEmailBodyFileName);
                // Zip files and place to stage for FTP service to pick up
                BuildZipSet.ZipSet();
            }
        }  // end of build
    }

    public static void PackageSubsDeliveryFiles(String [][] csvFiles) throws IOException {
        String csvFileListName = "", zipReturnFile = "";
        int listSize           = csvFiles[0].length;
        System.out.println("\nStarting to package file...");

        for (int x=listSize; x >0 ; x--) {                 // csv email files that were created before
            csvFileListName = csvFiles[0][x-1];

            if (csvFileListName != null){
                File f = new File(csvFileListName + ".csv");
                FileInputStream inStream = new FileInputStream(csvFileListName + ".csv");
                int inBytes = inStream.available();
                inStream.close();
                if (inBytes < 42){
                     f.delete();
                     f = null;
                     csvFileListName = null;
                }
            }
            if (csvFileListName != null){
                // move each csv file from stage to work directory including email body text
                BuildSubsDeliverSet(csvFileListName, cfgObj.pdfWorkDirectory);
                // create the command file with the updated command parameter
                BuildCommandFile(csvFileListName + ".csv", cfgObj.pdfEmailCommand, cfgObj.pdfEmailCommandFileName, cfgObj.pdfWorkDirectory);
                // Build the body file (created this function for future use)
                BuildBodyFile(cfgObj.pdfEmailTemplate, cfgObj.pdfWorkDirectory, cfgObj.pdfEmailBodyFileName);
                // Zip files and place to stage for FTP service to pick up
                BuildZipSet.ZipSubscriptionDelivery();
            }
        }  // end of build
    }

    public static void PackageAdhocDeliveryFiles(String [][] csvFiles) throws IOException  {
        String csvFileListName  = "", zipReturnFile = "";
        int listSize            = csvFiles[0].length;
        System.out.println("\nStarting to package file...");

        for (int x=0; x < listSize; x++) {                 // csv email files that were created before
            csvFileListName = csvFiles[0][x];

            if (csvFileListName != null){
                File f = new File(csvFileListName);
                FileInputStream inStream = new FileInputStream(csvFileListName + ".csv");
                int inBytes = inStream.available();
                inStream.close();
                if (inBytes < 42){
                     f.delete();
                     f = null;
                     csvFileListName = null;
                }
            }

            if (csvFileListName != null){
                // move each csv file from stage to work directory including email body text
                BuildDeliverAdhocSet(csvFileListName, cfgObj.pdfAdWorkDirectory);
                // create the command file with the updated command parameter
                BuildCommandFile(csvFileListName + ".csv", cfgObj.pdfAdEmailCommand, cfgObj.pdfAdEmailCommandFileName, cfgObj.pdfAdWorkDirectory);
                // Build the body file (created this function for future use)
                BuildBodyFile(cfgObj.pdfAdEmailTemplate, cfgObj.pdfAdWorkDirectory, cfgObj.pdfAdEmailBodyFileName);
                // Zip files and place to stage for FTP service to pick up
                BuildZipSet.ZipAdhocDelivery();
            }
        }  // end of build
    }

    public static void PackageBillReprintDeliveryFiles(String[] csvFiles, String mailMethod) throws IOException  {
        String csvFileListName  = "", zipReturnFile = "";
        int listSize            = csvFiles.length;
        System.out.println("\nStarting to package file...");

        for (int x=0; x < listSize; x++) {                 // csv files that were created before
            csvFileListName = csvFiles[x];

            if (csvFileListName != null){
                  File f = new File(csvFileListName);
                  FileInputStream inStream = new FileInputStream(csvFileListName + ".csv");
                  int inBytes = inStream.available();
                  inStream.close();

                  // move each csv file from stage to work directory
                  BuildReprintSet(csvFileListName, cfgObj.reprintWorkDirectory);
                  BuildZipSet.ZipReprintDelivery(mailMethod);
            }

        }  // end of build
    }

    public static void BuildFileSet(String packFileName, String workDir) { // move each CSV to work directory
        try {
      // File (or directory) to be moved, packFilename is each the CSV file
      File file = new File(packFileName);
      // Destination directory
      File dir  = new File(workDir);
      // Move file to new directory
      boolean success = file.renameTo(new File(dir, file.getName()));
      if (!success) {
                 System.out.println("Not Successful in moving file to " + dir);
        // File was not successfully moved
        // This file will be zeroed out by my BuildZipSet process since it is still lock
        }
      } catch (Exception ex) {
        System.out.print("Process Name(BuildFileSet)- " + ex.getClass() + " " + ex.getMessage());
      }
    }

    public static void BuildCommandFile(String newVal, String emailCommand, String commandFileName, String workDir){
        String lineFileReader     = "";
        try {
            RandomAccessFile raf  = new RandomAccessFile(emailCommand, "rw");
            //output to the work directory file
            RandomAccessFile oraf = new RandomAccessFile(workDir + commandFileName, "rw");
            System.out.println("Building the command file for..." + newVal);
            // Position yourself at the end of the file
            boolean lnvalue       = true;
            String line           = "";
            String srchvalue      = "[csvfile]";
            StringBuffer buff     = new StringBuffer(1024);
            newVal                = newVal.substring(newVal.lastIndexOf("/") + 1);
            while (lnvalue){
                line = raf.readLine();
                if (line == null){   //when end of file
                    lnvalue = false;
                }
                else{
                    int srchPos = line.indexOf(srchvalue);
                    buff.append(line);
                    if (srchPos != -1){
                        buff = buff.replace(srchPos, srchvalue.length() + srchPos, newVal);
                    }
                    line           = buff.toString();
                    lineFileReader = lineFileReader.concat(line);
                    //un-comment this together with the declare to output built msg into a file
                    oraf.seek(oraf.length());
                    oraf.writeBytes(line + "\r\n");
                }
                buff = buff.delete(0, buff.length());
            }
            oraf.close();
            raf.close();
        } catch (Exception ex) {
            System.out.print("Process Name(BuildCommandFile)- " + ex.getClass() + " " + ex.getMessage());
        }
    }

    public static void BuildBodyFile(String emailTemplate, String workDir, String bodyFileName){
        String lineFileReader = "";
        try {
            RandomAccessFile raf  = new RandomAccessFile(emailTemplate, "rw");
            //output to the work directory file
            RandomAccessFile oraf = new RandomAccessFile(workDir + bodyFileName, "rw");
            boolean lnvalue       = true;              // Position yourself at the end of the file
            String line           = "";
            StringBuffer buff     = new StringBuffer(1024);
            while (lnvalue){
                line              = raf.readLine();
                if (line == null){   //when end of file
                    lnvalue = false;
                }else{
                    oraf.seek(oraf.length());
                    oraf.writeBytes(line + "\r\n");
                }
            }
            oraf.close();
            raf.close();
        } catch (Exception ex) {
            System.out.println("Process Name(BuildBodyFile)- " + ex.getClass() + " " + ex.getMessage());
        }
    }

    public static void BuildSubsDeliverSet(String packFileName, String workDir) { // move each CSV to work directory
        int comparePos        = 0;
        String fileNameInDir  = "", fileCompareRoot="";
        File inDir            = new File(cfgObj.pdfStageDirectory);          // get a list of files from current directory
        String inFiles[]      = inDir.list();
        int srchPos           = packFileName.lastIndexOf("/");
        if (srchPos != -1){
            fileCompareRoot = packFileName.substring(srchPos + 1);
        }
        for (int i=0; i<inFiles.length; i++) {     // loop the files in the stage directory
            fileNameInDir = inFiles[i].toString();
            if (srchPos != -1){
                comparePos = fileNameInDir.indexOf(fileCompareRoot);
                if (comparePos != -1){
                    File file       = new File(cfgObj.pdfStageDirectory + fileNameInDir);
                    File dir        = new File(workDir);
                    boolean success = file.renameTo(new File(dir, file.getName())); // Move file to new directory
                }
            }
        }
    }

    public static void BuildDeliverAdhocSet(String packFileName, String workDir) { // move each CSV to work directory
        int comparePos       = 0;
        String fileNameInDir = "", fileCompareRoot="";
        File inDir           = new File(cfgObj.pdfAdStageDirectory);          // get a list of files from current directory
        String inFiles[]     = inDir.list();
        int srchPos          = packFileName.lastIndexOf("/");
        if (srchPos != -1){
            fileCompareRoot  = packFileName.substring(srchPos + 1); }
        for (int i=0; i<inFiles.length; i++) {     // loop the files in the stage directory
            fileNameInDir  = inFiles[i].toString();
            if (srchPos != -1){
                comparePos = fileNameInDir.indexOf(fileCompareRoot);
                if (comparePos != -1){
                    File file       = new File(cfgObj.pdfAdStageDirectory + fileNameInDir);
                    File dir        = new File(workDir);
                    boolean success = file.renameTo(new File(dir, file.getName())); // Move file to new directory
                }
            }
        }
    }

    public static void BuildReprintSet(String packFileName, String workDir) { // move each CSV to work directory
        int comparePos       = 0;
        String fileNameInDir = "", fileCompareRoot="";
        File inDir           = new File(cfgObj.reprintStageDirectory);          // get a list of files from current directory
        String inFiles[]     = inDir.list();
        int srchPos          = packFileName.lastIndexOf("/");
        if (srchPos != -1){
            fileCompareRoot  = packFileName.substring(srchPos + 1); }
        for (int i=0; i<inFiles.length; i++) {     // loop the files in the stage directory
            fileNameInDir  = inFiles[i].toString();
            if (srchPos != -1){
                comparePos = fileNameInDir.indexOf(fileCompareRoot);
                if (comparePos != -1){
                    File file       = new File(cfgObj.reprintStageDirectory + fileNameInDir);
                    File dir        = new File(workDir);
                    boolean success = file.renameTo(new File(dir, file.getName())); // Move file to new directory
                }
            }
        }
    }

    public static String checkCSVContent(String fileName) throws IOException {
        File f = new File(fileName);
        FileInputStream inStream = new FileInputStream(fileName);
        int inBytes = inStream.available();
        System.out.println(inBytes);
        inStream.close();
        if (inBytes < 42){
            f.delete();
            f = null;
            fileName = null;
        }
        return fileName;
    }
    public static String checkVUBContent(String fileName) throws IOException {
        File f = new File(fileName);
        FileInputStream inStream = new FileInputStream(fileName);
        int inBytes = inStream.available();
        inStream.close();
        if (inBytes < 9){
            f.delete();
            f = null;
            fileName = null;
        }
        return fileName;
    }
}
/*  -- use this to debug the files being process -- for future use!  *** DO NOT DELETE ***
             for (int i = 0; i < csvFiles[0].length; i++){
                 System.out.println(csvFiles[0][i]);
             }
             for (int i = 0; i < csvFiles[1].length; i++){
                System.out.println(csvFiles[1][i]);
             }
 */
